library(tidyverse)
argv=commandArgs()
merge = read_tsv(argv[6])

if(nrow(merge)==0)
  {merge=merge[c(1:15)]
  colnames(merge)=c('motif','TF','Chr','Positions','MNVID','Refs','Alts','rsIDs','Score_binding','P','Binding_start','Binding_end','context','Effect','Source')
  write.table(merge,file = argv[7],quote = F,col.names = T,row.names = F,sep = "\t")} else 
    {
merge = merge %>% separate(col = X4, into = c("Chr","Positions","MNVID","Refs","Alts","rsIDs"), sep = "_")
m1=merge %>% filter(X17=='Loss') %>% select_if(~ all(!is.na(.))) 
m2=merge %>% filter(X17=='Gain') %>% select_if(~ all(!is.na(.))) 
if(nrow(m1)==0) {m1=m1[c(1:(length(colnames(m1))-13),(length(colnames(m1))-6):length(colnames(m1)))] }
if(nrow(m2)==0) {m2=m2[c(1:(length(colnames(m2))-13),(length(colnames(m2))-6):length(colnames(m2)))] }
if(length(colnames(m1))<16 || length(colnames(m2))<16){
  if(nrow(m1)==0) {m1 = m1 %>% select(-X2)}
  if(nrow(m2)==0) {m2 = m2 %>% select(-X2)}
  colnames(m1)[9:15]=c('strand',  'Score_binding',  'P',       'Binding_start',   'Binding_end',     'context', 'Effect')
colnames(m2)[9:15]=c('strand',  'Score_binding',  'P',       'Binding_start',   'Binding_end',     'context', 'Effect')
m1 = m1 %>% mutate(across(.fns = as.character))
m2 = m2 %>% mutate(across(.fns = as.character))
m=m1 %>% bind_rows(m2)
colnames(m)[1]='motif'
colnames(m)[2]='TF'
m = m %>% select(-strand)
m$Source='hocomoco'
} else
  {
  colnames(m1)[10:16]=c('strand',  'Score_binding',  'P',       'Binding_start',   'Binding_end',     'context', 'Effect')
  colnames(m2)[10:16]=c('strand',  'Score_binding',  'P',       'Binding_start',   'Binding_end',     'context', 'Effect')
  m1 = m1 %>% mutate(across(.fns = as.character))
  m2 = m2 %>% mutate(across(.fns = as.character))
  m=m1 %>% bind_rows(m2)
  colnames(m)[1]='motif'
  colnames(m)[3]='TF'
  m$Source='jaspar'
  m = m %>% select(-strand)
  m = m %>% select(-X2)
}
write.table(m,file = argv[7],quote = F,col.names = T,row.names = F,sep = "\t")
}
